package com.yk.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信登录工具类
 */
public class WechatLoginUtil {



//    @Value("${APPID}")
//    private static String APPID;
//
//    @Value("${APPSECRET}")
//    private static String APPSECRET;
    // 小程序的 appid
    private static final String APPID = "wx0e460b69a128b1cd";
    // 小程序的 appsecret
    private static final String APPSECRET = "c5f42dc3e51b98fcf3a62f39d06e8247";
    // 微信登录凭证校验接口
    private static final String WECHAT_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 通过小程序临时登录凭证 code 获取 openid 和 session_key
     * @param code 小程序临时登录凭证
     * @return 包含 openid 和 session_key 的 Map
     */
    public static Map<String, String> getOpenIdAndSessionKey(String code) {
        Map<String, String> result = new HashMap<>();
        try {
            // 拼接请求 URL
            String requestUrl = WECHAT_LOGIN_URL + "?appid=" + APPID + "&secret=" + APPSECRET + "&js_code=" + code + "&grant_type=authorization_code";
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 解析响应
            JSONObject jsonObject = JSONObject.parseObject(response.toString());
            if (jsonObject.containsKey("openid") && jsonObject.containsKey("session_key")) {
                result.put("openid", jsonObject.getString("openid"));
                result.put("session_key", jsonObject.getString("session_key"));
            } else {
                // 处理错误
                result.put("errorCode", jsonObject.getString("errcode"));
                result.put("errorMsg", jsonObject.getString("errmsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 解密微信用户手机号
     * @param encryptedData 加密数据
     * @param sessionKey 会话密钥
     * @param iv 加密算法的初始向量
     * @return 解密后的手机号
     * @throws Exception 解密异常
     */
    public static String decryptPhoneNumber(String encryptedData, String sessionKey, String iv) throws Exception {
        byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);
        byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey);
        byte[] ivBytes = Base64.getDecoder().decode(iv);

        SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKeyBytes, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

        byte[] decryptedBytes = cipher.doFinal(encryptedDataBytes);

        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

}